package com.snopzyz.hello.databus.utils;

import com.github.shyiko.mysql.binlog.event.DeleteRowsEventData;
import com.github.shyiko.mysql.binlog.event.EventData;
import com.github.shyiko.mysql.binlog.event.UpdateRowsEventData;
import com.github.shyiko.mysql.binlog.event.WriteRowsEventData;
import com.snopzyz.hello.databus.domain.Column;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
public class BinlogUtils {

    public static Map<String, Column> getColMap (String db, String table) {
        //获取数据源
        DataSource dataSource =  SpringBeanUtils.getBean(DataSource.class);
        // 待执行SQL
        String preSql = "SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, COLUMN_KEY, DATA_TYPE, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? and TABLE_NAME = ?";

        try (Connection connection = dataSource.getConnection();
             PreparedStatement ps = connection.prepareStatement(preSql)) {
            ps.setString(1, db);
            ps.setString(2, table);

            try (ResultSet rs = ps.executeQuery()) {
                return Column.getTableFrom(rs);
            }
        } catch (SQLException e) {
            log.error("load db conf error, db_table={}:{} ", db, table, e);
            return null;
        }
    }

    public static String getDbTable (String db, String table) {
        return db + "-" + table;
    }

    public static String getDb (String dbTable) {
        return dbTable.split("-")[0];
    }

    public static String getTable (String dbTable) {
        return dbTable.split("-")[1];
    }


    public static long getTableId (EventData eventData) {
        if (eventData instanceof WriteRowsEventData) {
            return ((WriteRowsEventData) eventData).getTableId();
        }
        if (eventData instanceof UpdateRowsEventData) {
            return ((UpdateRowsEventData) eventData).getTableId();
        }
        if (eventData instanceof DeleteRowsEventData) {
            return ((DeleteRowsEventData) eventData).getTableId();
        }
        return -1L;
    }
}
